package com.calm.editor.parse;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

import com.calm.editor.api.TemplateService;
import com.calm.editor.entity.Template;
import com.calm.editor.entity.TemplateKey;
public class TagXmlParser implements InitializingBean {
	private Resource[] namespaces;
	@javax.annotation.Resource
	private TemplateService templateService;
	
	@Override
	public void afterPropertiesSet()  {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (Resource r:namespaces) {
					InputStream inputStream = null;
					try {
						if(r.isReadable()){
							inputStream = r.getInputStream();
							SAXReader saxReader = new SAXReader();
							Document document = saxReader.read(inputStream);
							Element root = document.getRootElement();
							parse(root);
							
						}
					} catch (IOException | DocumentException e) {
						e.printStackTrace();
					}finally{
						org.apache.commons.io.IOUtils.closeQuietly(inputStream);
					}
				}
			}
		}).start();
		
	}
	
	public Resource[] getNamespaces() {
		return namespaces;
	}

	public void setNamespaces(Resource[] namespaces) {
		this.namespaces = namespaces;
	}
	
	@SuppressWarnings("unchecked")
	private void parse(Element root ){
		String uri = root.attributeValue("uri");
		Iterator<Element> selectNodes = root.elementIterator("tag");
		TemplateKey templateKey = new TemplateKey();
		templateKey.setNamespace(uri);
		while(selectNodes.hasNext()){
			Element tagNode = selectNodes.next();
			String name = tagNode.attributeValue("name");
			
			templateKey.setTagName(name);
			Template byId = templateService.getById(templateKey);
			
			if(byId==null){
				byId = new Template();
				byId.setId(templateKey);
				templateService.save(byId);
			}
			StringBuilder builder=new StringBuilder("<ul>");
			processAttr(tagNode,builder);
			builder.append("</ul>");
			byId.setTemplate(builder.toString());
			
			templateService.update(byId);

		}
	}
	@SuppressWarnings("unchecked")
	private void processAttr(Element tagNode, StringBuilder builder) {
		Iterator<Element> selectNodes = tagNode.elementIterator("attr");
		while(selectNodes.hasNext()){
			Element attrNode = selectNodes.next();
			Element element = attrNode.element("template");
			String text = element.getTextTrim();
			builder.append("<li>");
			builder.append(text);
			builder.append("</li>");
		}
	}
}
